import { throttle } from 'lodash'

/**
 * @param binding.value 激活拖拽功能的元素className
 */
export const VDrag = {
    mounted(el: HTMLElement, binding: any) {
        // 鼠标在拖拽目标元素内部的位置
        let x = 0;
        let y = 0;
        let isDragging = false;
        const handleMouseDown = (event: MouseEvent) => {
            isDragging = true;
            x = event.clientX - el.offsetLeft;
            y = event.clientY - el.offsetTop;
            document.addEventListener("mousemove", throttle(handleMouseMove, 15));
            document.addEventListener("mouseup", handleMouseUp);
        };
        const handleMouseMove = (event: MouseEvent) => {
            if (isDragging) {
                let newLeft = event.clientX - x;
                let newTop = event.clientY - y;
                if (newLeft < 0) {
                    newLeft = 0;
                }
                if (newTop < 0) {
                    newTop = 0;
                }
                if (newLeft + el.offsetWidth > window.innerWidth) {
                    newLeft = window.innerWidth - el.offsetWidth;
                }
                if (newTop + el.offsetHeight > window.innerHeight) {
                    newTop = window.innerHeight - el.offsetHeight;
                }
                el.style.left = `${newLeft}px`;
                el.style.top = `${newTop}px`;
            }
        };
        const handleMouseUp = () => {
            isDragging = false;
            document.removeEventListener("mousemove", handleMouseMove);
            document.removeEventListener("mouseup", handleMouseUp);
        };
        if (binding.value) {
            let els: HTMLElement[] = el.getElementsByClassName(binding.value) as any
            if (els.length) {
                els[0].addEventListener("mousedown", handleMouseDown);
            }
        } else {
            el.addEventListener("mousedown", handleMouseDown);
        }
    }
};
